package com.edgardeng.work_queues;

import com.edgardeng.ConnectionUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;

/**
 * RabbitMQ 测试 Work Queues - 消费者接收消息
 *
 */
public class ReceiverTwo {

    public static void main(String[] args) throws Exception {
        String QUEUE_NAME = ConnectionUtil.QUEUE_NAME_WORK_QUEUE;

        // 获取连接，声明通道和队列
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        channel.basicQos(1); // accept only one unack-ed message at a time (see below)
        System.out.println(" [Receiver Tw0] Waiting for messages. To exit press CTRL+C");
        // 声明一个回调
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            try {
                Thread.sleep(10);
            }catch (InterruptedException e) {
                e.printStackTrace();
            }
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [Receiver Tw0] Received '" + message + "'");
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); // arg2: false:接收, true: 拒绝
        };
        // 接收消息 arg1：队列名 arg2 是否自动确认，arg3 接收回调 arg4 取消回调
        channel.basicConsume(QUEUE_NAME, false, deliverCallback, consumerTag -> { });

    }
}
